package train_service

import (
	"fmt"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/utils/tools"
	"sort"

	"github.com/gin-gonic/gin"
)

const (
	TidType = "academy"
)

// 请求类
type CfgReq struct {
	Tid  int    `json:"tid" form:"tid"`
	Sid  int    `json:"sid" form:"sid"`
	Type string `json:"type" form:"type"`
}

type GetupReq struct {
	ConstituteId uint `json:"constitute_id" form:"constitute_id"`
}

// 返回信息

type CfgInfoResp struct {
	Id     uint            `json:"id"`
	Type   string          `json:"type"`
	Name   string          `json:"name"`
	Option []model.CfgInfo `json:"option"`
}

type TrainResp struct {
	Type  string          `json:"type"`
	Value []model.CfgInfo `json:"value"`
}

type TrainService struct{}

// 根据学校信息获取
func TrainGetAcademyUnion(ctx *gin.Context) (out []interface{}, err error) {

	uid, exists := ctx.Get("uid")
	if !exists {
		return out, fmt.Errorf("操作失败~")
	}
	us, _ := tables.GetAgentInfoByUid(uid.(uint))
	school := us.School
	// 根据学校查询学校Id
	var cons tables.Constitute
	d := variable.DB.MySQL.Where("type = 'school' and name = ?", school).Find(&cons)
	if d.RowsAffected == 0 {
		return out, fmt.Errorf("该学校查询错误")
	}
	schoolId := int(cons.ID)
	// 根据学校id获取信息
	c, _ := tables.GetChildSecondLevelById(schoolId)
	mmp := c.Member
	for i := 0; i < len(mmp); i++ {
		var cir = CfgInfoResp{}
		var cfgInfos = []model.CfgInfo{}
		cir.Id = mmp[i].ID
		cir.Type = "academy"
		cir.Name = mmp[i].Name // 学院
		ret, _ := tables.GetChildSecondLevelById(int(mmp[i].ID))
		pmmp := ret.Member
		for j := 0; j < len(pmmp); j++ {
			if len(pmmp[j].Name) != 0 {
				var cio = model.CfgInfo{}
				cio.Id = pmmp[j].ID
				cio.Type = "profession"
				cio.Name = pmmp[j].Name
				cfgInfos = append(cfgInfos, cio)
			}
		}
		cir.Option = cfgInfos
		out = append(out, cir)
	}
	return out, nil
}

// 根据type获取config sid是学校id  tid 是学院belong_to_id
func GetTrainConfig(ctx *gin.Context, typ string, tid int, sid int) (out TrainResp, err error) {
	// 如果是school 查询该学校下面的学院信息
	// 如果是academy  根据tid查询该学院下面的专业信息
	// 如果是profession  根据tid查询该
	uid, exists := ctx.Get("uid")
	if !exists {
		return out, fmt.Errorf("操作失败~")
	}
	us, _ := tables.GetAgentInfoByUid(uid.(uint))
	school := us.School
	level := us.Level
	// 如果是超级用户
	if us.Type == tables.UserTypeSadmin {
		if sid != 0 {
			ci, _ := new(tables.Constitute).GetConstituteById(sid)
			school = ci.Name
		}
	}

	var cons tables.Constitute
	// 判断该用户的身份, 如果是超级用户，需要根据选择的学校进行查询
	if us.Type != tables.UserTypeSadmin {
		d := variable.DB.MySQL.Where("type = 'school' and name = ?", school).Find(&cons)
		if d.RowsAffected == 0 {
			return out, fmt.Errorf("该学校查询错误")
		}
		sid = int(cons.ID)
	}

	var cfi []model.CfgInfo
	out.Type = typ
	out.Value = make([]model.CfgInfo, 0)
	// 根据 constitute_id
	consMap, _ := new(tables.Constitute).GetupConfigMap(us.ConstituteID)
	if typ == "school" {
		if level == tables.RolesLevel4 { // 专业管理员
			cfi = append(cfi, model.CfgInfo{Id: consMap[tables.SchoolType].Id, Type: consMap[tables.SchoolType].Type, Name: consMap[tables.SchoolType].Name})
		} else if level == tables.RolesLevel3 { // 学院管理员
			cfi = append(cfi, model.CfgInfo{Id: consMap[tables.SchoolType].Id, Type: consMap[tables.SchoolType].Type, Name: consMap[tables.SchoolType].Name})
		} else if us.Type != tables.UserTypeSadmin {
		} else {
			if tid != 0 {
				return out, nil
			} else {
				cf, _ := new(tables.Constitute).GetConstituteByType("school")
				cfi = append(cfi, cf...)
			}
		}

		cfi = append(cfi, model.CfgInfo{Id: 0, Type: "school", Name: "全部学校"})
		out.Value = cfi
	} else if typ == "academy" {
		if level == tables.RolesLevel4 { // 专业管理员
			cfi = append(cfi, model.CfgInfo{Id: consMap[tables.AcademyType].Id, Type: consMap[tables.AcademyType].Type, Name: consMap[tables.AcademyType].Name})
			cfi = append(cfi, model.CfgInfo{Id: 0, Type: "academy", Name: "全部学院"})
		} else if level == tables.RolesLevel3 { // 学院管理员
			cfi = append(cfi, model.CfgInfo{Id: consMap[tables.AcademyType].Id, Type: consMap[tables.AcademyType].Type, Name: consMap[tables.AcademyType].Name})
			cfi = append(cfi, model.CfgInfo{Id: 0, Type: "academy", Name: "全部学院"})
		} else {
			if tid != 0 {
				cfi, _ = new(tables.Constitute).GetConstituteByBelongToId(tid)
				cfi = append(cfi, model.CfgInfo{Id: 0, Type: "academy", Name: "全部学院"})
			} else {
				cfi, _ = new(tables.Constitute).GetConstituteByBelongToId(sid)
				cfi = append(cfi, model.CfgInfo{Id: 0, Type: "academy", Name: "全部学院"})
			}
		}
		out.Value = cfi
	} else if typ == "profession" { // 获取学院 和 专业
		if level == tables.RolesLevel4 { // 专业管理员
			cfi = append(cfi, model.CfgInfo{Id: consMap[tables.ProfessionType].Id, Type: consMap[tables.ProfessionType].Type, Name: consMap[tables.ProfessionType].Name})
			cfi = append(cfi, model.CfgInfo{Id: 0, Type: "profession", Name: "全部专业"})
			out.Value = cfi
		} else {
			if tid != 0 {
				cfi, _ = new(tables.Constitute).GetConstituteByBelongToId(tid)
				cfi = append(cfi, model.CfgInfo{Id: 0, Type: "profession", Name: "全部专业"})
				out.Value = cfi
			} else {
				// 首先判断
				if tid == 0 && sid != 0 {
					cf, _ := new(tables.Constitute).GetInfoByShoolId(sid)
					cfi = append(cfi, cf...)
				}
				var value []model.CfgInfo
				var nameArr []string
				for i := 0; i < len(cfi); i++ {
					if tools.Contains(nameArr, cfi[i].Name) {
						continue
					}
					var cfg model.CfgInfo
					cfg.Id = cfi[i].Id
					cfg.Type = "profession"
					cfg.Name = cfi[i].Name
					value = append(value, cfg)
					nameArr = append(nameArr, cfi[i].Name)
				}
				value = append(value, model.CfgInfo{Id: 0, Type: "profession", Name: "全部专业"})
				out.Value = value
			}
		}
	} else if typ == "career" {
		// 定义career
		var crs []tables.Career
		if tid != 0 {
			d := variable.DB.MySQL.Where("id = ?", tid).Find(&crs)
			if d.RowsAffected == 0 {
				return out, nil
			}
		} else {
			d := variable.DB.MySQL.Find(&crs)
			if d.RowsAffected == 0 {
				return out, nil
			}
		}
		for i := 0; i < len(crs); i++ {
			var c model.CfgInfo
			c.Type = "career"
			c.Name = crs[i].Name
			c.Id = crs[i].ID
			cfi = append(cfi, c)
		}
		cfi = append(cfi, model.CfgInfo{Id: 0, Type: "career", Name: "全部职业"})
		out.Value = cfi
	}
	sort.Slice(out.Value, func(i, j int) bool {
		return out.Value[i].Id < out.Value[j].Id
	})
	return out, nil
}

// 根据consitituteID 获取 gradeId  professionId  academyId
func (c *TrainService) GetupConfig(ctx *gin.Context, gr GetupReq) (model.GetupResp, error) {
	consId := gr.ConstituteId
	out, err := new(tables.Constitute).GetupConfig(consId)
	return out, err
}
